/**
 * 
 */
package com.zznode.client.wlanpolling.test;

import java.io.ByteArrayInputStream;

import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Node;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.model.TestResult;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.service.net.HttpCallback;
import com.zznode.client.wlanpolling.service.net.HttpException;
import com.zznode.client.wlanpolling.service.xml.XmlXPathAdaptor;
import com.zznode.client.wlanpolling.utils.PingUtils;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;

/**
 * @author Pink
 * 
 */
public class PollTestResultActivity extends Activity implements HttpCallback {
	public static final int TAG_POST_TESTRESULT = 1;
	public static final int TAG_POST_WIRELESSEVN = 2;
	
	private ProgressDialog pBar;
	private WLANPollingApplication application;
	private Integer _id = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.polltestresult);
		
		application = (WLANPollingApplication)getApplication();
		bindEvent();
	}

	@Override
	protected void onResume() {
		Intent intent = getIntent();
		initParams(intent);
		super.onResume();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		initParams(intent);
		super.onNewIntent(intent);
	}
	
	private void initParams(Intent intent) {
		if(intent != null && intent.getExtras() != null &&
				intent.getExtras().get("_id") != null) {
			_id = (Integer)intent.getExtras().get("_id");
		} else {
			_id = -1;
		}
			
		initTestResultData();
	}

	private void initTestResultData() {
		TestResult testResult = null;
		
		if(_id == null || _id < 0) {
			testResult = WLANPollManager.getWLANPollManager()
				.getTestResult();
		} else {
			testResult = WLANPollManager.getWLANPollManager().getTestResult(this, _id);
		}
		
		TextView ipAddress = (TextView) findViewById(R.id.ipAddress);
		ipAddress.setText(testResult.ipAddress);

		TextView averageRate = (TextView) findViewById(R.id.averageRate);
		averageRate.setText(testResult.averageRate!=null ? testResult.averageRate + "KB/s":"");
		
		TextView peekRate = (TextView) findViewById(R.id.peekRate);
		peekRate.setText(testResult.peekRate!=null?testResult.peekRate + "KB/s":"");

		TextView apnettimelag = (TextView) findViewById(R.id.apnettimelag);
		apnettimelag.setText(testResult.apnettimelag!=null?testResult.apnettimelag + "ms":"");

		TextView apnetloss = (TextView) findViewById(R.id.apnetloss);
		apnetloss.setText(testResult.apnetloss!=null?testResult.apnetloss + "%":"");

		TextView netskytimelag = (TextView) findViewById(R.id.netskytimelag);
		netskytimelag.setText(testResult.netskytimelag!=null?testResult.netskytimelag + "ms":"");

		TextView netskyloss = (TextView) findViewById(R.id.netskyloss);
		netskyloss.setText(testResult.netskyloss!=null?testResult.netskyloss + "%":"");

		TextView uploadSpeed = (TextView) findViewById(R.id.uploadSpeed);
		uploadSpeed.setText(testResult.uploadSpeed!=null?testResult.uploadSpeed+"KB/s":"");

		TextView uploadDatasize = (TextView) findViewById(R.id.uploadDatasize);
		uploadDatasize.setText(testResult.uploadDatasize!=null?testResult.uploadDatasize+"KB":"");

		TextView downloadSpeed = (TextView) findViewById(R.id.downloadSpeed);
		downloadSpeed.setText(testResult.downloadSpeed!=null?testResult.downloadSpeed+"KB/s":"");

		TextView downloadDatasize = (TextView) findViewById(R.id.downloadDatasize);
		downloadDatasize.setText(testResult.downloadDatasize!=null?testResult.downloadDatasize+"KB":"");

		TextView devAp1 = (TextView) findViewById(R.id.devAp1);
		devAp1.setText(testResult.devAp1);

		TextView devAp2 = (TextView) findViewById(R.id.devAp2);
		devAp2.setText(testResult.devAp2);

		TextView changetimelag = (TextView) findViewById(R.id.changetimelag);
		changetimelag.setText(testResult.changetimelag!=null?testResult.changetimelag+"ms":"");

		TextView changeloss = (TextView) findViewById(R.id.changeloss);
		changeloss.setText(testResult.changeloss!=null?testResult.changeloss:"");

		TextView manualPingParams = (TextView)findViewById(R.id.manualPingParams);
		manualPingParams.setText(testResult.manualPingParams!=null?testResult.manualPingParams:"");
		
		TextView manualPingDelay = (TextView) findViewById(R.id.manualPingDelay);
		manualPingDelay.setText(testResult.manualPingDelay!=null?testResult.manualPingDelay + "ms":"");

		TextView manualPingLossPackage = (TextView) findViewById(R.id.manualPingLossPackage);
		manualPingLossPackage.setText(testResult.manualPingLossPackage!=null?testResult.manualPingLossPackage:"");

//		TextView relTestCount = (TextView) findViewById(R.id.relTestCount);
//		relTestCount.setText(testResult.relTestCount!=null?testResult.relTestCount:"");
//
//		TextView relTestDelay = (TextView) findViewById(R.id.relTestDelay);
//		relTestDelay.setText(testResult.relTestDelay!=null?testResult.relTestCount + "ms":"");

		// 场点1
		TextView rssiremark1 = (TextView) findViewById(R.id.rssiremark1);
		rssiremark1.setText(testResult.rssiremark1 != null?testResult.rssiremark1.toString():"");

		TextView rssival1 = (TextView) findViewById(R.id.rssival1);
		rssival1.setText(testResult.rssival1 !=null ? testResult.rssival1 + "dBm" : "");

		TextView snrval1 = (TextView) findViewById(R.id.snrval1);
		snrval1.setText(testResult.snrval1 != null ? testResult.snrval1 + "dB" : "");

		TextView delayval1 = (TextView) findViewById(R.id.delayval1);
		delayval1.setText(testResult.delayval1 !=null ? testResult.delayval1 + "ms": "");

		TextView packlostval1 = (TextView) findViewById(R.id.packlostval1);
		packlostval1.setText(testResult.packlostval1!=null?testResult.packlostval1:"");

		// 场点2
		TextView rssiremark2 = (TextView) findViewById(R.id.rssiremark2);
		rssiremark2.setText(testResult.rssiremark2 != null?testResult.rssiremark2.toString():"");

		TextView rssival2 = (TextView) findViewById(R.id.rssival2);
		rssival2.setText(testResult.rssival2 !=null ? testResult.rssival2 + "dBm" : "");

		TextView snrval2 = (TextView) findViewById(R.id.snrval2);
		snrval2.setText(testResult.snrval2 != null ? testResult.snrval2 + "dB" : "");

		TextView delayval2 = (TextView) findViewById(R.id.delayval2);
		delayval2.setText(testResult.delayval2 !=null ? testResult.delayval2 + "ms": "");

		TextView packlostval2 = (TextView) findViewById(R.id.packlostval2);
		packlostval2.setText(testResult.packlostval2!=null?testResult.packlostval2:"");

		// 场点3
		TextView rssiremark3 = (TextView) findViewById(R.id.rssiremark3);
		rssiremark3.setText(testResult.rssiremark3 != null?testResult.rssiremark3.toString():"");

		TextView rssival3 = (TextView) findViewById(R.id.rssival3);
		rssival3.setText(testResult.rssival3 !=null ? testResult.rssival3 + "dBm" : "");

		TextView snrval3 = (TextView) findViewById(R.id.snrval3);
		snrval3.setText(testResult.snrval3 != null ? testResult.snrval3 + "dB" : "");

		TextView delayval3 = (TextView) findViewById(R.id.delayval3);
		delayval3.setText(testResult.delayval3 !=null ? testResult.delayval3 + "ms": "");

		TextView packlostval3 = (TextView) findViewById(R.id.packlostval3);
		packlostval3.setText(testResult.packlostval3!=null?testResult.packlostval3:"");

		// 场点4
		TextView rssiremark4 = (TextView) findViewById(R.id.rssiremark4);
		rssiremark4.setText(testResult.rssiremark4 != null?testResult.rssiremark4.toString():"");

		TextView rssival4 = (TextView) findViewById(R.id.rssival4);
		rssival4.setText(testResult.rssival4 !=null ? testResult.rssival4 + "dBm" : "");

		TextView snrval4 = (TextView) findViewById(R.id.snrval4);
		snrval4.setText(testResult.snrval4 != null ? testResult.snrval4 + "dB" : "");

		TextView delayval4 = (TextView) findViewById(R.id.delayval4);
		delayval4.setText(testResult.delayval4 !=null ? testResult.delayval4 + "ms": "");

		TextView packlostval4 = (TextView) findViewById(R.id.packlostval4);
		packlostval4.setText(testResult.packlostval4!=null?testResult.packlostval4:"");

	}
	
	private void bindEvent() {
		Button btn = (Button)findViewById(R.id.btnSubmit);
		btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showProgressbar();
				postTestResult();
			}
		});
	}
	
	private void postTestResult() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				pBar.setMessage("正在交测试结果...");
			}
		});
		SharedPreferences preferences =  getSharedPreferences(WLanPollingUtils.USER_INFO, 0);
	    String username = preferences.getString(WLanPollingUtils.USERNAME, " ");
		WLANPollManager.getWLANPollManager().postTestResult(PollTestResultActivity.this, PollTestResultActivity.TAG_POST_TESTRESULT, username);
	}
	
	private void postWirelessEnv() {
		//TODO
		WLANPollManager.getWLANPollManager().getWirelessEnvResult(application.getApplicationContext(), 
				PingUtils.clearMacAdress(application.getContext().getCurrentWifi().getBSSID()));
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				pBar.setMessage("正在提交无线环境数据...");
			}
		});
		WLANPollManager.getWLANPollManager().postWirelessEnv(PollTestResultActivity.this, PollTestResultActivity.TAG_POST_WIRELESSEVN);
	}
	
	@Override
	public void onReceiveData(byte[] data, final HttpException exp, int tag) {
		
		if(tag == PollTestResultActivity.TAG_POST_TESTRESULT) {
			if(exp != null) {
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(PollTestResultActivity.this, "测试结果提交失败, 原因:" + exp.getMessage(), Toast.LENGTH_LONG).show();
					}
				});
				return;
			}
			
			try {
				XmlXPathAdaptor xPath = new XmlXPathAdaptor(new ByteArrayInputStream(data));
				//Node updateStatus = (Node)xPath.evaluate("/NODE/UPDATE_STATUS", XPathConstants.NODE);
				
				Node resultCode = (Node)xPath.evaluate("/NODE/RESULT_CODE", XPathConstants.NODE);
				String status = resultCode.getAttributes().getNamedItem("name").getNodeValue();
				if(status != null && "1".equals(status)) {
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(PollTestResultActivity.this, "测试结果提交成功!", Toast.LENGTH_LONG).show();
						}
					});
				} else {
					String value = resultCode.getTextContent();
					throw new Exception("测试结果提交失败!原因:" + value);
				}
			} catch (final Exception e) {
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(PollTestResultActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
					}
				});
			} finally {
				postWirelessEnv();
			}
		} else if(tag == PollTestResultActivity.TAG_POST_WIRELESSEVN) {
			if(exp != null) {
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(PollTestResultActivity.this, "无线环境信息提交失败, 原因:" + exp.getMessage(), Toast.LENGTH_LONG).show();
					}
				});
				return;
			}
			
			try {
				XmlXPathAdaptor xPath = new XmlXPathAdaptor(new ByteArrayInputStream(data));
				Node resultCode = (Node)xPath.evaluate("/NODE/RESULT_CODE", XPathConstants.NODE);
				String status = resultCode.getAttributes().getNamedItem("name").getNodeValue();
				
				if(status != null && "1".equals(status)) {
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(PollTestResultActivity.this, "无线环境信息结果提交成功!", Toast.LENGTH_LONG).show();
						}
					});
				} else {
					String value = resultCode.getTextContent();
					throw new Exception("无线环境测试结果提交失败!原因:" + value);
				}
			} catch (final Exception e) {
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(PollTestResultActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
					}
				});
			} finally {
				runOnUiThread(new Runnable() {
					public void run() {
						//取消进度条
						if(pBar != null) {
							pBar.cancel();
							pBar = null;
						}
					}
				});
			}
		}
	}
	
	private void showProgressbar() {
		
		pBar = new ProgressDialog(this);
		pBar.setTitle("提示");
		pBar.setMessage("在提交测试结果,请稍候...");
		pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pBar.show();
	}
}
